from machine import I2C


class I2CIOWrapper(object): 

    class I2CReadError(Exception):
        pass

    class I2CWriteError(Exception):
        pass

    def __init__(self, i2c, slaveaddr):
        if not isinstance(i2c, I2C):
            raise TypeError("`i2c` should be machine.I2C type")
        self.__i2c = i2c
        self.__slaveaddr = slaveaddr

    def __str__(self):
        return "{}(0x{:X}) device".format(type(self).__name__, self.__slaveaddr)
    
    def read(self, reg, size=1, delay=0):
        if size <= 0:
            raise ValueError("`size` should be greater than 0")
        data = bytearray(size)
        if self.__i2c.read(self.__slaveaddr, reg, len(reg), data, size, delay) != 0:
            raise self.I2CReadError("{} read {} failed".format(self, reg))
        return data

    def write(self, reg, data):
        if not isinstance(data, (bytearray, bytes)):
            raise TypeError("`data` should be bytearray or bytes")
        if self.__i2c.write(self.__slaveaddr, reg, len(reg), data, len(data)) != 0:
            raise self.I2CWriteError("{} write {}, {} failed".format(self, reg, data))
